package com.warm.pump.executor.batch;

import org.springframework.batch.core.JobExecution;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;

/**
 * Created by guozj on 2018/1/22.
 */
@Component
public class LogMonitoringNotifier {

    private String formatExceptionMessage(Throwable exception) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        exception.printStackTrace(new PrintStream(baos));
        return baos.toString();
    }

    private String createMessageContent(JobExecution jobExecution) {
        List<Throwable> exceptions = jobExecution.getAllFailureExceptions();
        StringBuilder content = new StringBuilder();
        content.append("  Job execution #");
        content.append(jobExecution.getId());
        content.append(" of job instance #");
        content.append(jobExecution.getJobInstance().getId());
        content.append(" failed with following exceptions:");
        for (Throwable exception : exceptions) {
            content.append("/n");
            content.append(formatExceptionMessage(exception));
        }
        return content.toString();
    }

    public String notify(JobExecution jobExecution) {
        String content = createMessageContent(jobExecution);
        return content;
    }
}